package com.hjt.utils;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

import javax.imageio.ImageIO;

import com.hjt.constants.Const;

public class FileUtil {
	public static File createImg(BufferedImage buff) {
		File f = new File(Const.FILE_SAVE_BASE_PATH + "/log/" + String.valueOf(System.currentTimeMillis()) + ".png");
		if (!f.getParentFile().exists()) {
			f.getParentFile().mkdirs();
		}
		try {
			ImageIO.write(buff, "png", f);
			return f;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static File createImgAndPoint(BufferedImage buff, Point p) {
		String prefix = Const.FILE_SAVE_BASE_PATH + "/log/" + String.valueOf(System.currentTimeMillis());
		File orginal = new File(prefix + ".png");
		if (!orginal.getParentFile().exists()) {
			orginal.getParentFile().mkdirs();
		}
		try {
			ImageIO.write(buff, "png", orginal);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		Graphics g = buff.getGraphics();
		g.setColor(Color.RED);
		g.fill3DRect(p.x - 5, p.y - 5, 10, 10, false);

		File hasPoint = new File(prefix + "_p.png");
		try {
			ImageIO.write(buff, "png", hasPoint);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return orginal;
	}

	public static byte[] readBytesFromFile(File file) {
		byte[] bytesArray = new byte[(int) file.length()];
		try (FileInputStream fis = new FileInputStream(file)) {
			fis.read(bytesArray); // 将文件内容读入 byte 数组
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return bytesArray;
	}

	public static String convertToBase64(String imagePath) throws IOException {
		InputStream imageInputStream = new FileInputStream(imagePath);
		byte[] imageBytes = new byte[imageInputStream.available()];
		imageInputStream.read(imageBytes);
		imageInputStream.close();
		return Base64.getEncoder().encodeToString(imageBytes);
	}
	public static void main(String[] args) {
		try {
			System.out.println(convertToBase64("e://1746776601922.jpg"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
